<!-- 订单消息提醒展示，在layout/components/Navbar.vue文件中引用 -->
<template>
  <div class="main-wrapper">
    <el-badge :value="badgeInfo" class="item">
      <el-button size="small" @click="showOrder">查看订单</el-button>
    </el-badge>
  </div>
</template>

<script>
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import store from '@/store'

export default {
  name: 'OrderMsg',
  data() {
    // 存放数据
    return {
      stompClient: null,
      timer: '',
      badgeInfo: '',
      sellerId: store.getters.orgId
    }
  },
  // 生命周期 - 创建完成
  created() {
    this.initWebSocket()
  },
  beforeDestroy() {
    // 页面离开时断开连接,清除定时器
    this.disconnect()
    clearInterval(this.timer)
  },
  // 方法
  methods: {
    initWebSocket() {
      this.connection()
      const that = this
      // 断开重连机制,尝试发送消息,捕获异常发生时重连
      this.timer = setInterval(() => {
        try {
          that.stompClient.send('ping')
        } catch (err) {
          console.log('断线了: ' + err)
          that.connection()
        }
      }, 5000)
    },
    connection() {
      // 建立连接对象
      const socket = new SockJS('http://localhost:8090/hjk_ws')
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(socket)
      // 定义客户端的认证信息,按需求配置
      const headers = {
        // 'H-TOKEN': '861e3dc2-aca5-4f6d-83c1-8f869382e1c6'
      }
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, () => {
        this.stompClient.subscribe('/chat/order/' + this.sellerId, (msg) => { // 订阅服务端提供的某个topic
          const msgInfo = JSON.parse(msg.body) // msg.body存放的是服务端发送给我们的信息
          const tableId = msgInfo.tableId
          const orderId = msgInfo.orderId
          store.dispatch('order/addOrderList', { tableId, orderId })
          this.badgeInfo = 'new'
        }, headers)
      }, (err) => {
        // 连接发生错误时的处理函数
        console.log('失败')
        console.log(err)
      })
    }, // 连接 后台
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect()
      }
    }, // 断开连接
    showOrder() {
      this.badgeInfo = ''
      // this.$store.dispatch('tagsView/delView', this.$route)
      this.$router.push('/dashboard')
    }
  }
}
</script>
<style lang='scss' scoped>
// @import url(); // 引入公共css类
.main-wrapper {
  margin: 8px;
}
</style>
